//
//  FeatureTableViewController.m
//  IceBreaker
//
//  Created by 老焦 on 12-10-16.
//  Copyright (c) 2012年 NDS. All rights reserved.
//

#import "FeatureTableViewController.h"
#import "CustomFeatureCell.h"
#import "EventDetailViewController.h"
#import "NSData+Base64.h"

@interface FeatureTableViewController ()

@end

@implementation FeatureTableViewController

@synthesize mySocket;
@synthesize serverIP;
@synthesize connectPort;
@synthesize connectTime;
@synthesize nowLocation;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        self.title = @"Feature";
        // read configuration from bundle
        serverIP = [[NSUserDefaults standardUserDefaults] stringForKey: @"connectHost"];
        connectPort = [[NSUserDefaults standardUserDefaults] integerForKey: @"connectPort"];
        connectTime = [[NSUserDefaults standardUserDefaults] doubleForKey: @"connectTimeout"];
        NSLog(@"Configuration read: HOST:[%@], PORT:[%d], TIMEOUT:[%f]", serverIP, connectPort, connectTime);
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    /*
    NSString *latitude = [NSString stringWithFormat: @"%f", nowLocation.coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat: @"%f", nowLocation.coordinate.longitude];
    NSString *altitude = [NSString stringWithFormat: @"%f", nowLocation.altitude];
    
    NSLog(@"当前位置三维信息，经度：%@，纬度：%@，海拔：%@。", latitude, longitude, altitude);
    */
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    if (nil == headerView) {
        EGORefreshHeaderView *egoView = [[EGORefreshHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
        egoView.delegate = self;
        [self.tableView addSubview: egoView];
        headerView = egoView;
        [egoView release];
    }
    
    //  update the last update date
	[headerView refreshLastUpdatedDate];
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    headerView = nil;
    mySocket = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"CustomFeatureCellIdentifier";
    
    CustomFeatureCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
    if (cell == nil) {
        UIImage *eventImg = [UIImage imageNamed: @"detail1.png"];
        if ([indexPath row] % 2 == 0) {
            eventImg = [UIImage imageNamed: @"detail2.png"];
        }
        cell = [[[CustomFeatureCell alloc] initWithEventImg: eventImg
                                                    headImg: [UIImage imageNamed: @"head.png"]
                                                 eventTitle: @"不如一起来一场 2v2 的男女混双网球赛不如一起来一场 2v2 的男女混双网球赛不如一起来一场 2v2 的男女混双网球赛"
                                                       name: @"legend"
                                                     gender: 0
                                                        age: 27
                                                  eventType: @"Movement"
                                                   distance: 5.5
                                            reuseIdentifier: CellIdentifier] autorelease];
        
        
        cell.selectedBackgroundView = [[[UIView alloc] initWithFrame:cell.frame] autorelease];
        cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
    }
    // [];
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    NSLog(@"~~~~11~~~~%@~~~~", self.parentViewController);
    NSLog(@"~~~~22~~~~%@~~~~", self.presentedViewController);
    NSLog(@"~~~~33~~~~%@~~~~", self.presentingViewController);

    EventDetailViewController *detailView = [[EventDetailViewController alloc] initWithNibName: @"EventDetailViewController"
                                                                                        bundle: nil];
    detailView.hidesBottomBarWhenPushed = YES;
    [self.parentViewController.navigationController pushViewController: detailView
                                         animated: YES];
    // [self.view removeFromSuperview];
    [detailView release];
}

-(CGFloat) tableView: (UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *)indexPath {
    UITableViewCell *cell = [self tableView: tableView cellForRowAtIndexPath: indexPath];
    return cell.frame.size.height;
}

-(void) setParentViewController:(UIViewController *) viewController {
    // [self setParentViewController: viewController];
    [self setValue: viewController forKey: @"_parentViewController"];
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods
-(void) tableViewDataSourceLoading {	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
    NSLog(@"A valid Scroll acted here, it's time to request the data from the server now.");

     NSData *codeData = [@"A1" dataUsingEncoding: NSUTF8StringEncoding];
     NSString *encodedCode = [NSData encodeBase64: codeData];
     NSData *latitudeData = [@"22.5" dataUsingEncoding: NSUTF8StringEncoding];
     NSString *encodedLatitude = [NSData encodeBase64: latitudeData];
     NSData *longitudeData = [@"133.8" dataUsingEncoding: NSUTF8StringEncoding];
     NSString *encodedLogitude = [NSData encodeBase64: longitudeData];
     NSData *altitudeData = [@"-5.5" dataUsingEncoding: NSUTF8StringEncoding];
     NSString *encodedAltitude = [NSData encodeBase64: altitudeData];
     NSData *UidData = [@"7001" dataUsingEncoding: NSUTF8StringEncoding];
     NSString *encodedUid = [NSData encodeBase64: UidData];
     NSData *pageData = [@"3" dataUsingEncoding: NSUTF8StringEncoding];
     NSString *encodedPage = [NSData encodeBase64: pageData];
     NSData *typeData = [@"Movement" dataUsingEncoding: NSUTF8StringEncoding];
     NSString *encodedType = [NSData encodeBase64: typeData];
     NSData *otherData = [@"Other filter" dataUsingEncoding: NSUTF8StringEncoding];
     NSString *encodedOther = [NSData encodeBase64: otherData];
     
     NSString *sendStr = [encodedCode stringByAppendingString: @";"];
     sendStr = [sendStr stringByAppendingString: encodedLatitude];
     sendStr = [sendStr stringByAppendingString: @";"];
     sendStr = [sendStr stringByAppendingString: encodedLogitude];
     sendStr = [sendStr stringByAppendingString: @";"];
     sendStr = [sendStr stringByAppendingString: encodedAltitude];
     sendStr = [sendStr stringByAppendingString: @";"];
     sendStr = [sendStr stringByAppendingString: encodedUid];
     sendStr = [sendStr stringByAppendingString: @";"];
     sendStr = [sendStr stringByAppendingString: encodedPage];
     sendStr = [sendStr stringByAppendingString: @";"];
     sendStr = [sendStr stringByAppendingString: encodedType];
     sendStr = [sendStr stringByAppendingString: @";"];
     sendStr = [sendStr stringByAppendingString: encodedOther];
     sendStr = [sendStr stringByAppendingString: @";"];
     sendStr = [sendStr stringByAppendingFormat: @"\r\n"];
     NSLog(@"String to be send~~~~%@~~~~", sendStr);
     
     NSData *dataToSend = [sendStr dataUsingEncoding: NSISOLatin1StringEncoding];
     [mySocket writeData: dataToSend
             withTimeout: connectTime
                     tag: 0];
     
     NSLog(@"Temporary donot try to read anything frm the server."); 

	loading = YES;	
}

-(void)tableViewDataSourceLoaded {
    NSLog(@"Data loaded, here it's time to make the table reload the data now.");
	//  model should call this when its done loading
	loading = NO;
	[headerView egoRefreshScrollViewDataSourceDidFinishedLoading: self.tableView];
	
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    // NSLog(@"Scrolled the view, either up or down!");
	[headerView egoRefreshScrollViewDidScroll:scrollView];    
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    // NSLog(@"The view finished scrolling(your finger left the screen), either up or down!");
	[headerView egoRefreshScrollViewDidEndDragging:scrollView];	
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

-(void)egoHeaderDidTriggerRefresh:(EGORefreshHeaderView*)view{
    NSLog(@"egoHeaderDidTriggerRefresh started");
	[self tableViewDataSourceLoading];
	[self performSelector: @selector(tableViewDataSourceLoaded) 
               withObject: nil 
               afterDelay: 3.0];
    NSLog(@"egoHeaderDidTriggerRefresh finished");
	
}

-(BOOL)egoHeaderDataSourceIsLoading:(EGORefreshHeaderView *)view{	
	return loading; // should return if data source model is reloading
	
}

-(NSDate*)egoHeaderDataSourceLastUpdated:(EGORefreshHeaderView *)view{	
	return [NSDate date]; // should return date data source was last changed
	
}

#pragma mark - methods for connection delegate
-(int) createConnection: (NSString *)hostIP
                   port: (UInt16)hostPort
                timeout: (NSTimeInterval) timeout {
    if (nil == mySocket) {
        mySocket = [[AsyncSocket alloc] initWithDelegate: self];
        NSError *error = nil;

        if (![mySocket connectToHost: hostIP
                              onPort: hostPort
                         withTimeout: timeout
                               error: &error]) {
            NSLog(@"Something wrong with the connection, error code is [%d] and the error reads [%@]. Please check the network.", [error code], [error localizedDescription]);;
            return CONNECTION_FAIL;
        } else {
            NSLog(@"The connection is OK, we can use the socket now.");
            return CONNECTION_SUC;
        }
    } else {
        [mySocket readDataWithTimeout: connectTime
                                  tag: 0];
        return SRV_CONNECTED;
    }
}

-(IBAction)reConnect:(NSString *) hostIP
                port:(UInt16)hostPort
             timeout:(NSTimeInterval)timeout {
    int stateCode = [self createConnection: hostIP
                                      port: hostPort
                                   timeout: timeout];
    switch (stateCode) {
		case CONNECTION_SUC:
            NSLog(@"Connection connected successfully");
			break;
		case SRV_CONNECTED:
			NSLog(@"Connection is already connected");
			break;
		default:
			break;
	}
}

#pragma mark socket delegate

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
	[mySocket readDataWithTimeout: -1 
                              tag: 0];
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    [mySocket disconnect];
    NSLog(@"Error");
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
	NSLog(@"Sorry this connect is failure, close the socket.");
	mySocket = nil;
}

- (void)onSocketDidSecure:(AsyncSocket *)sock{
	
}

-(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
    NSLog(@"thread(%@),onSocket:%p didWriteDataWithTag:%ld",[[NSThread currentThread] name], sock, tag);
}

- (void)onSocket: (AsyncSocket *)sock
     didReadData: (NSData *)data
         withTag: (long)tag{
	
	NSString* aStr = [[NSString alloc] initWithData: data
                                           encoding: NSUTF8StringEncoding];
	NSLog(@"Data recieved is [%@]",aStr);
	[mySocket readDataWithTimeout: -1 
                              tag: 0];
}

@end
